<?php

namespace App\Console\Commands;

use App\Models\WeChat;
use App\Models\WechatCumulative;
use App\Models\WechatUser;
use App\Models\WechatUserRecord;
use Illuminate\Console\Command;
use EasyWeChat\Foundation\Application;
use Doctrine\Common\Cache\PredisCache;

class getRecords extends Command
{
    protected $openPlatform = '';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'get:record';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取用户数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {

        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(Application $app)
    {

        $predis = app('redis')->connection()->client();// connection($name), $name 默认为 `default`
        $cacheDriver = new PredisCache($predis);
        $app->cache = $cacheDriver;
        $wechat = WeChat::query()->get();
        $openPlatform = $app->open_platform;
        \Log::info('执行获取记录');
        foreach ($wechat as $item) {
            $apps = $openPlatform->createAuthorizerApplication($item->authorizer_appid, $item->authorizer_refresh_token);
            $stats = $apps->stats;
            $from = date('Y-m-d', strtotime(-7 . 'day'));
            $to = date('Y-m-d', strtotime(-1 . 'day'));
            $userSummary = $stats->userSummary($from, $to);
            if (!empty($userSummary['list'])) {
                foreach ($userSummary['list'] as $values) {
                    //dd($value);
                    $record = WechatUserRecord::query()
                        ->where(['ref_date' => $values['ref_date'], 'w_id' => $item->id, 'user_source' => $values['user_source']])
                        ->first();
                    if (!$record) {
                        $record = new WechatUserRecord();
                    }
                    $record->user_source = $values['user_source'];
                    $record->ref_date = $values['ref_date'];
                    $record->w_id = $item->id;
                    $record->times = strtotime($values['ref_date']);
                    $record->new_user = $values['new_user'];
                    $record->cancel_user = $values['cancel_user'];
                    if (!$record->save()) {
                        \log::info(var_dump($values) . '记录添加失败');
                        //  echo var_dump($values).'记录添加失败';
                    } else {
                        \log::info(var_dump($values) . '记录添加成功');
                        //   echo var_dump($values).'记录添加成功';
                    }
                }
            }
            $cumulatives = $stats->userCumulate($from, $to);
            if (!empty($cumulatives['list'])) {
                foreach ($cumulatives['list'] as $value) {
                    //dd($value);
                    $record = WechatCumulative::query()
                        ->where(['ref_date' => $value['ref_date'], 'w_id' => $item->id])
                        ->first();
                    if (!$record) {
                        $record = new WechatCumulative();
                    }
                    $record->ref_date = $value['ref_date'];
                    $record->w_id = $item->id;
                    $record->times = strtotime($value['ref_date']);
                    $record->user_number = $value['cumulate_user'];
                    if (!$record->save()) {
                        \Log::info(var_dump($value) . '记录添加失败');
                        //  echo var_dump($value).'记录添加失败';
                    } else {
                        \Log::info(var_dump($value) . '记录添加成功');
                        // echo var_dump($value).'记录添加成功';
                    }
                }
            }
            $userService = $apps->user;
            $Wechat_users = $userService->lists();
                foreach ($Wechat_users['data']['openid'] as $user_item) {
                    $user_logs = $userService->get($user_item);
                    $wechat_user = WechatUser::query()->where(['open_id' => $user_item])->first();
                    if (!$wechat_user) {
                        $wechat_user = new WechatUser();
                    }
                    if(isset($user_logs->subscribe)&&$user_logs->subscribe == 1) {
                        $wechat_user->w_id = $item->id;
                        $wechat_user->nick_name = $user_logs->nickname;
                        $wechat_user->sex = 2;
                        $wechat_user->city = $user_logs->city;
                        $wechat_user->country = $user_logs->country;
                        $wechat_user->province = $user_logs->province;
                        $wechat_user->headimgurl = $user_logs->headimgurl;
                        $wechat_user->open_id = $user_logs->openid;
                        $wechat_user->subscribe_time = $user_logs->subscribe_time;
                        $wechat_user->remark = $user_logs->remark;
                        $wechat_user->groupid = $user_logs->groupid;
                        $wechat_user->tagid_list = empty($user_logs->tagid_list) ? '' : json_encode($user_logs->tagid_list);
                        if (!$wechat_user->save()) {
                            \Log::info($wechat_user->getErrors());
                        } else {
                            \Log::info($wechat_user->toArray());
                        }
                    }
                }

        }

    }

}

